<?php
class it_user_role_model extends MY_Model {
	var $model = 'it_user_role';
	
	function GetUserRole($as_userid='')
	{
		$ls_sql	= "	SELECT	d.*, e.app_name,
							(CASE WHEN EXISTS(SELECT 1 FROM it_user_role x WHERE x.user_id='".$as_userid."' AND x.role_id=d.role_id) THEN '1' ELSE '0' END) checked
					FROM	it_role d
							JOIN it_application e ON d.app_id = e.app_id
					ORDER BY d.app_id, d.role_name";
		$result	= $this->db->query($ls_sql);
		if($result->num_rows() > 0){
			return $result->result_array();
		}else{
			return NULL;
		}
	}
	
	function SetUserRole($as_userid='')
	{
		$this->db->delete('it_user_role', array('user_id' => $as_userid));
		
		$arr_role = $this->GetUserRole($as_userid);
		for($i=0,$max_i=count($arr_role); $i<$max_i; $i++){
			$row = $arr_role[$i];
			if(strtolower(post('role_'.$row['role_id']))=='on'){
				$this->db->insert('it_user_role', array('user_id' => $as_userid, 'role_id' => $row['role_id']));
			}
		}
		
		$this->db->delete('IT_USER_APPLICATION', array('USER_ID' => $as_userid));
		//$this->db->query("DELETE FROM IT_USER_APPLICATION WHERE USER_ID = '".$as_userid."'");
		$this->db->query("INSERT INTO IT_USER_APPLICATION (USER_ID, APP_ID) SELECT DISTINCT A.USER_ID,B.APP_ID FROM IT_USER_ROLE A JOIN IT_ROLE B ON A.ROLE_ID = B.ROLE_ID WHERE A.USER_ID = '".$as_userid."'");
		
	}
}
?>